<template>
  <div class="parent-dashboard">
    <el-card class="welcome-card" shadow="never">
      <div class="welcome-content">
        <h2>欢迎，{{ userStore.userInfo?.realName }} 家长</h2>
        <p class="welcome-desc">您可以在这里查看孩子的档案和学习情况</p>
      </div>
    </el-card>

    <!-- 孩子列表 -->
    <el-card class="children-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <el-icon :size="20"><UserFilled /></el-icon>
          <span>我的孩子</span>
        </div>
      </template>

      <div v-loading="loading">
        <el-empty v-if="!children || children.length === 0" 
                  description="暂无关联的学生信息" 
                  :image-size="100">
          <el-alert
            title="提示"
            type="info"
            :closable="false"
            show-icon
          >
            请联系学生或管理员完成家长绑定
          </el-alert>
        </el-empty>

        <div v-else class="children-list">
          <el-card 
            v-for="child in children" 
            :key="child.id" 
            shadow="hover" 
            class="child-card"
          >
            <div class="child-info">
              <el-avatar :size="80" :src="child.avatar" class="child-avatar">
                <el-icon :size="40"><UserFilled /></el-icon>
              </el-avatar>
              <div class="child-details">
                <h3>{{ child.realName }}</h3>
                <div class="detail-item">
                  <el-icon><Postcard /></el-icon>
                  <span>学号：{{ child.studentNo }}</span>
                </div>
                <div class="detail-item">
                  <el-icon><School /></el-icon>
                  <span>{{ child.deptName }} - {{ child.className }}</span>
                </div>
                <div class="detail-item">
                  <el-icon><Calendar /></el-icon>
                  <span>入学：{{ child.enrollDate || '-' }}</span>
                </div>
                <div class="detail-item">
                  <el-tag :type="getStatusType(child.status)" size="small">
                    {{ child.statusText }}
                  </el-tag>
                </div>
              </div>
            </div>

            <!-- 学习概况 -->
            <el-divider />
            <div class="child-stats">
              <div class="stat-item">
                <div class="stat-label">平均分</div>
                <div class="stat-value">{{ child.averageScore || '-' }}</div>
              </div>
              <div class="stat-item">
                <div class="stat-label">总学分</div>
                <div class="stat-value">{{ child.totalCredits || '-' }}</div>
              </div>
              <div class="stat-item">
                <div class="stat-label">已修课程</div>
                <div class="stat-value">{{ child.courseCount || '-' }}</div>
              </div>
            </div>

            <!-- 档案信息 -->
            <el-divider content-position="left">档案信息</el-divider>
            <el-descriptions :column="2" size="small" border>
              <el-descriptions-item label="性别">{{ child.genderText }}</el-descriptions-item>
              <el-descriptions-item label="年龄">{{ child.age ? child.age + ' 岁' : '-' }}</el-descriptions-item>
              <el-descriptions-item label="出生日期">{{ child.birthday || '-' }}</el-descriptions-item>
              <el-descriptions-item label="入学年份">{{ child.enrollYear ? child.enrollYear + ' 级' : '-' }}</el-descriptions-item>
              <el-descriptions-item label="班主任">{{ child.headTeacherName || '-' }}</el-descriptions-item>
              <el-descriptions-item label="联系电话">{{ child.phone || '-' }}</el-descriptions-item>
              <el-descriptions-item label="家庭住址" :span="2">{{ child.address || '-' }}</el-descriptions-item>
            </el-descriptions>

            <!-- 操作按钮 -->
            <el-divider />
            <div class="action-buttons">
              <el-button type="primary" :icon="Reading" @click="viewScores(child)">
                查看成绩
              </el-button>
              <el-button type="success" :icon="Download" @click="exportScores(child)">
                导出成绩
              </el-button>
              <el-button type="info" :icon="Document" @click="viewRecords(child)">
                查看档案记录
              </el-button>
            </div>
          </el-card>
        </div>
      </div>
    </el-card>

    <!-- 成绩预览对话框 -->
    <el-dialog
      v-model="scoresDialogVisible"
      :title="`${currentChild?.realName} - 成绩列表`"
      width="80%"
      :close-on-click-modal="false"
    >
      <div v-loading="scoresLoading">
        <div class="dialog-actions">
          <el-button type="success" :icon="Download" @click="exportScores(currentChild)">
            导出成绩Excel
          </el-button>
        </div>
        
        <el-table :data="scoresList" stripe border style="width: 100%; margin-top: 15px">
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column prop="courseName" label="课程名称" min-width="120" />
          <el-table-column prop="score" label="成绩" width="80" align="center">
            <template #default="{ row }">
              <el-tag :type="getScoreType(row.score)">{{ row.score }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="credit" label="学分" width="80" align="center" />
          <el-table-column prop="semester" label="学期" width="100" align="center" />
          <el-table-column prop="examType" label="考试类型" width="100" align="center">
            <template #default="{ row }">
              <el-tag size="small">{{ row.examType || '期末考试' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="teacherName" label="任课教师" width="100" />
          <el-table-column prop="createTime" label="录入时间" width="160" />
          <el-table-column prop="remark" label="备注" min-width="120" show-overflow-tooltip />
        </el-table>

        <el-pagination
          v-if="scoresTotal > 0"
          v-model:current-page="scoresCurrent"
          v-model:page-size="scoresSize"
          :total="scoresTotal"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="loadScoresPage"
          @size-change="loadScoresPage"
          style="margin-top: 15px; justify-content: center;"
        />

        <el-empty v-if="!scoresLoading && scoresList.length === 0" description="暂无成绩记录" />
      </div>
    </el-dialog>

    <!-- 档案记录预览对话框 -->
    <el-dialog
      v-model="recordsDialogVisible"
      :title="`${currentChild?.realName} - 档案记录`"
      width="80%"
      :close-on-click-modal="false"
    >
      <div v-loading="recordsLoading">
        <div class="dialog-actions">
          <el-button type="success" :icon="Download" @click="exportRecords(currentChild)">
            导出档案记录Excel
          </el-button>
        </div>

        <el-table :data="recordsList" stripe border style="width: 100%; margin-top: 15px">
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column prop="recordTypeName" label="记录类型" width="120" align="center">
            <template #default="{ row }">
              <el-tag :type="getRecordTypeColor(row.recordType)">
                {{ row.recordTypeName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="content" label="记录内容" min-width="200" show-overflow-tooltip />
          <el-table-column prop="recordDate" label="记录日期" width="120" align="center" />
          <el-table-column prop="creatorName" label="记录人" width="100" />
          <el-table-column prop="createTime" label="创建时间" width="160" />
        </el-table>

        <el-pagination
          v-if="recordsTotal > 0"
          v-model:current-page="recordsCurrent"
          v-model:page-size="recordsSize"
          :total="recordsTotal"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="loadRecordsPage"
          @size-change="loadRecordsPage"
          style="margin-top: 15px; justify-content: center;"
        />

        <el-empty v-if="!recordsLoading && recordsList.length === 0" description="暂无档案记录" />
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  UserFilled,
  School,
  Calendar,
  Postcard,
  Reading,
  Download,
  Document
} from '@element-plus/icons-vue'
import { useUserStore } from '@/store/user'
import request from '@/utils/request'

const userStore = useUserStore()

const loading = ref(false)
const children = ref<any[]>([])

// 成绩对话框相关
const scoresDialogVisible = ref(false)
const scoresLoading = ref(false)
const scoresList = ref<any[]>([])
const scoresTotal = ref(0)
const scoresCurrent = ref(1)
const scoresSize = ref(10)
const currentChild = ref<any>(null)

// 档案记录对话框相关
const recordsDialogVisible = ref(false)
const recordsLoading = ref(false)
const recordsList = ref<any[]>([])
const recordsTotal = ref(0)
const recordsCurrent = ref(1)
const recordsSize = ref(10)

/**
 * 加载关联的学生信息
 */
const loadChildren = async () => {
  loading.value = true
  try {
    const response = await request({
      url: '/parent/children',
      method: 'get'
    })
    children.value = response || []
  } catch (error: any) {
    console.error('加载学生信息失败', error)
    ElMessage.error(error?.message || '加载失败')
    children.value = []
  } finally {
    loading.value = false
  }
}

/**
 * 获取状态类型
 */
const getStatusType = (status: number) => {
  const typeMap: Record<number, string> = {
    1: 'success',  // 在籍
    2: 'warning',  // 休学
    3: 'info',     // 毕业
    4: 'danger'    // 退学
  }
  return typeMap[status] || ''
}

/**
 * 查看成绩
 */
const viewScores = (child: any) => {
  currentChild.value = child
  scoresCurrent.value = 1
  scoresSize.value = 10
  scoresDialogVisible.value = true
  loadScoresPage()
}

/**
 * 加载成绩分页数据
 */
const loadScoresPage = async () => {
  if (!currentChild.value) return
  
  scoresLoading.value = true
  try {
    const response = await request({
      url: `/parent/child/${currentChild.value.studentId}/scores`,
      method: 'get',
      params: { 
        current: scoresCurrent.value, 
        size: scoresSize.value 
      }
    })
    
    scoresList.value = response.records || []
    scoresTotal.value = response.total || 0
  } catch (error: any) {
    ElMessage.error(error?.message || '加载成绩失败')
    scoresList.value = []
    scoresTotal.value = 0
  } finally {
    scoresLoading.value = false
  }
}

/**
 * 获取成绩类型样式
 */
const getScoreType = (score: number) => {
  if (score >= 90) return 'success'
  if (score >= 80) return ''
  if (score >= 60) return 'warning'
  return 'danger'
}

/**
 * 导出成绩
 */
const exportScores = (child: any) => {
  const token = localStorage.getItem('token')
  window.open(
    `/api/parent/child/${child.studentId}/export-scores?satoken=${token}`,
    '_blank'
  )
  ElMessage.success('正在导出成绩...')
}

/**
 * 查看档案记录
 */
const viewRecords = (child: any) => {
  currentChild.value = child
  recordsCurrent.value = 1
  recordsSize.value = 10
  recordsDialogVisible.value = true
  loadRecordsPage()
}

/**
 * 加载档案记录分页数据
 */
const loadRecordsPage = async () => {
  if (!currentChild.value) return
  
  recordsLoading.value = true
  try {
    const response = await request({
      url: `/parent/child/${currentChild.value.studentId}/records`,
      method: 'get',
      params: { 
        current: recordsCurrent.value, 
        size: recordsSize.value 
      }
    })
    
    recordsList.value = response.records || []
    recordsTotal.value = response.total || 0
  } catch (error: any) {
    ElMessage.error(error?.message || '加载档案记录失败')
    recordsList.value = []
    recordsTotal.value = 0
  } finally {
    recordsLoading.value = false
  }
}

/**
 * 获取记录类型颜色
 */
const getRecordTypeColor = (recordType: number) => {
  const colorMap: Record<number, string> = {
    1: 'success',  // 奖励
    2: 'danger',   // 处分
    3: 'warning',  // 请假
    4: '',         // 活动
    5: 'info'      // 其他
  }
  return colorMap[recordType] || ''
}

/**
 * 导出档案记录
 */
const exportRecords = (child: any) => {
  const token = localStorage.getItem('token')
  window.open(
    `/api/parent/child/${child.studentId}/export-records?satoken=${token}`,
    '_blank'
  )
  ElMessage.success('正在导出档案记录...')
}

onMounted(() => {
  loadChildren()
})
</script>

<style scoped lang="scss">
.parent-dashboard {
  padding: 24px;
  background: linear-gradient(180deg, #f8f9fa 0%, #e9ecef 100%);
  min-height: calc(100vh - 60px);

  .welcome-card {
    margin-bottom: 24px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border: none;
    border-radius: 16px;
    overflow: hidden;
    box-shadow: 0 8px 24px rgba(102, 126, 234, 0.25);

    .welcome-content {
      padding: 40px;

      h2 {
        margin: 0 0 12px 0;
        font-size: 32px;
        font-weight: 600;
        letter-spacing: -0.5px;
      }

      .welcome-desc {
        margin: 0;
        font-size: 16px;
        opacity: 0.92;
        font-weight: 300;
      }
    }

    :deep(.el-card__body) {
      padding: 0;
    }
  }

  .children-card {
    margin-bottom: 24px;
    border-radius: 16px;
    border: none;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    transition: all 0.3s ease;

    &:hover {
      box-shadow: 0 4px 20px rgba(0, 0, 0, 0.12);
      transform: translateY(-2px);
    }

    .card-header {
      display: flex;
      align-items: center;
      gap: 10px;
      font-size: 18px;
      font-weight: 600;
      color: #2c3e50;
      
      .el-icon {
        color: #667eea;
      }
    }

    .children-list {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(480px, 1fr));
      gap: 24px;

      .child-card {
        height: 100%;
        border-radius: 12px;
        border: 1px solid #e8e8e8;
        transition: all 0.3s ease;
        background: white;

        &:hover {
          box-shadow: 0 6px 16px rgba(102, 126, 234, 0.15);
          border-color: #667eea;
        }

        .child-info {
          display: flex;
          gap: 24px;
          align-items: flex-start;
          padding-bottom: 20px;

          .child-avatar {
            flex-shrink: 0;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
          }

          .child-details {
            flex: 1;

            h3 {
              margin: 0 0 14px 0;
              font-size: 22px;
              font-weight: 600;
              color: #2c3e50;
              letter-spacing: -0.3px;
            }

            .detail-item {
              display: flex;
              align-items: center;
              gap: 8px;
              margin-bottom: 10px;
              color: #5a6c7d;
              font-size: 14px;
              line-height: 1.6;

              .el-icon {
                color: #909399;
                font-size: 16px;
              }
            }
          }
        }

        .child-stats {
          display: flex;
          justify-content: space-around;
          gap: 24px;
          margin: 20px 0;
          padding: 20px;
          background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
          border-radius: 12px;

          .stat-item {
            text-align: center;
            flex: 1;

            .stat-label {
              font-size: 13px;
              color: #6c757d;
              margin-bottom: 8px;
              font-weight: 500;
              text-transform: uppercase;
              letter-spacing: 0.5px;
            }

            .stat-value {
              font-size: 28px;
              font-weight: 700;
              color: #667eea;
              background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
              -webkit-background-clip: text;
              -webkit-text-fill-color: transparent;
              background-clip: text;
            }
          }
        }

        :deep(.el-descriptions) {
          margin-top: 20px;
          
          .el-descriptions__header {
            margin-bottom: 16px;
          }
          
          .el-descriptions__body {
            background: white;
          }
        }

        :deep(.el-divider) {
          margin: 24px 0;
        }

        .action-buttons {
          display: flex;
          gap: 12px;
          justify-content: center;
          flex-wrap: wrap;
          margin-top: 20px;
          padding-top: 20px;
          border-top: 1px solid #f0f0f0;

          .el-button {
            flex: 1;
            min-width: 130px;
            height: 40px;
            font-weight: 500;
            border-radius: 8px;
            transition: all 0.3s ease;

            &:hover {
              transform: translateY(-2px);
              box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            }
          }
        }
      }
    }

    :deep(.el-empty) {
      padding: 60px 20px;
    }
  }

  // 响应式
  @media (max-width: 768px) {
    padding: 12px;

    .children-list {
      grid-template-columns: 1fr !important;
    }

    .child-info {
      flex-direction: column;
      align-items: center !important;
      text-align: center;
    }
  }

  // 对话框样式
  .dialog-actions {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    margin-bottom: 16px;
    
    .el-button {
      height: 36px;
      padding: 0 24px;
      border-radius: 8px;
      font-weight: 500;
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
      }
    }
  }

  :deep(.el-dialog) {
    border-radius: 16px;
    box-shadow: 0 12px 48px rgba(0, 0, 0, 0.18);
    
    .el-dialog__header {
      padding: 24px 24px 16px;
      border-bottom: 1px solid #f0f0f0;
      
      .el-dialog__title {
        font-size: 20px;
        font-weight: 600;
        color: #2c3e50;
      }
    }
    
    .el-dialog__body {
      padding: 24px;
    }
    
    .el-table {
      font-size: 14px;
      border-radius: 8px;
      overflow: hidden;
      
      th {
        background: #f8f9fa;
        font-weight: 600;
        color: #2c3e50;
      }
    }
    
    .el-pagination {
      display: flex;
      justify-content: center;
      
      .el-pager li {
        border-radius: 6px;
        
        &.is-active {
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
      }
    }
  }
}
</style>

